package com.yonyougov.devops.cruxcisupport.component;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.SpringTemplateLoader;
import org.springframework.web.context.ServletContextAware;

import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import java.io.StringWriter;
import java.util.Map;

/**
 * Created by ligson on 2016/5/24.
 */
@Component
@Slf4j
public class TemplateEngine implements ApplicationContextAware, ServletContextAware {
    private static Configuration cfg = new Configuration(Configuration.getVersion());
    private ApplicationContext applicationContext;
    private ServletContext servletContext;

    @SneakyThrows
    @PostConstruct
    public void init() {
        //File file = applicationContext.getResource("classpath:ftl/deploy.ftl").getFile();
        //log.debug(file.getAbsolutePath());
        //log.debug(file.getParentFile().getAbsolutePath());
        cfg.setTemplateLoader(new SpringTemplateLoader(applicationContext, "classpath:ftl/"));
        //cfg.setServletContextForTemplateLoading(servletContext, "ftl");
        //cfg.setDirectoryForTemplateLoading(file.getParentFile());
        cfg.setNumberFormat("#");
        cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.getVersion()));
    }


    @SneakyThrows
    public String write(String templateName, Map<String, Object> varMap) {
        Template temp = cfg.getTemplate(templateName, "UTF-8");
        StringWriter stringWriter = new StringWriter();
        temp.process(varMap, stringWriter);
        return stringWriter.toString();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }
}
